<template>
  <div class="message-page">
    <van-nav-bar title="消息中心" />
    
    <van-tabs v-model:active="activeTab" sticky>
      <van-tab title="全部">
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
          <van-list
            v-model:loading="loading"
            :finished="finished"
            finished-text="没有更多消息"
            @load="onLoad"
          >
            <div class="message-list">
              <MessageItem 
                v-for="message in messages" 
                :key="message.id" 
                :data="message" 
                @click="onMessageClick(message)" 
              />
            </div>
            
            <div v-if="messages.length === 0 && !loading" class="empty-state">
              <van-empty description="暂无消息" />
            </div>
          </van-list>
        </van-pull-refresh>
      </van-tab>
      
      <van-tab title="系统通知">
        <van-pull-refresh v-model="refreshingSystem" @refresh="onRefreshSystem">
          <div class="message-list">
            <MessageItem 
              v-for="message in systemMessages" 
              :key="message.id" 
              :data="message" 
              @click="onMessageClick(message)" 
            />
          </div>
          
          <div v-if="systemMessages.length === 0" class="empty-state">
            <van-empty description="暂无系统通知" />
          </div>
        </van-pull-refresh>
      </van-tab>
      
      <van-tab title="评论">
        <van-pull-refresh v-model="refreshingComment" @refresh="onRefreshComment">
          <div class="message-list">
            <MessageItem 
              v-for="message in commentMessages" 
              :key="message.id" 
              :data="message" 
              @click="onMessageClick(message)" 
            />
          </div>
          
          <div v-if="commentMessages.length === 0" class="empty-state">
            <van-empty description="暂无评论消息" />
          </div>
        </van-pull-refresh>
      </van-tab>
      
      <van-tab title="点赞">
        <van-pull-refresh v-model="refreshingLike" @refresh="onRefreshLike">
          <div class="message-list">
            <MessageItem 
              v-for="message in likeMessages" 
              :key="message.id" 
              :data="message" 
              @click="onMessageClick(message)" 
            />
          </div>
          
          <div v-if="likeMessages.length === 0" class="empty-state">
            <van-empty description="暂无点赞消息" />
          </div>
        </van-pull-refresh>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import MessageItem from '../../components/message/MessageItem.vue'

const router = useRouter()

// 当前激活的标签页
const activeTab = ref(0)

// 消息列表数据
const messages = ref([])
const page = ref(1)
const pageSize = ref(10)
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)

// 系统消息相关
const refreshingSystem = ref(false)
const systemMessages = computed(() => messages.value.filter(msg => msg.type === 'system'))

// 评论消息相关
const refreshingComment = ref(false)
const commentMessages = computed(() => messages.value.filter(msg => msg.type === 'comment'))

// 点赞消息相关
const refreshingLike = ref(false)
const likeMessages = computed(() => messages.value.filter(msg => msg.type === 'like'))

// 加载消息数据
const loadMessages = async (isRefresh = false) => {
  if (isRefresh) {
    page.value = 1
    messages.value = []
    finished.value = false
  }
  
  loading.value = true
  
  try {
    // 实际项目中应该调用真实的API
    // const { data } = await get('/api/messages', {
    //   page: page.value,
    //   pageSize: pageSize.value
    // })
    
    // 模拟数据
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    const mockData = Array(pageSize.value).fill(0).map((_, index) => {
      const types = ['system', 'comment', 'like', 'follow']
      const type = types[Math.floor(Math.random() * types.length)]
      
      return {
        id: `${page.value}-${index}`,
        type,
        title: type === 'system' ? '系统通知' : '',
        content: type === 'system' 
          ? '感谢您使用我们的应用，祝您使用愉快！' 
          : '这是一条消息内容，可能是评论、点赞或关注的通知。这是一条消息内容，可能是评论、点赞或关注的通知。',
        isRead: Math.random() > 0.3,
        createTime: new Date(Date.now() - Math.floor(Math.random() * 7 * 24 * 60 * 60 * 1000)).toISOString(),
        sender: {
          id: `user-${index}`,
          name: `用户${index}`,
          avatar: `https://picsum.photos/id/${1000 + index}/100/100`
        }
      }
    })
    
    if (isRefresh) {
      messages.value = mockData
    } else {
      messages.value.push(...mockData)
    }
    
    // 判断是否加载完成
    if (page.value >= 3) {
      finished.value = true
    }
    
    page.value++
  } catch (error) {
    console.error('加载消息失败:', error)
    showToast('加载消息失败')
  } finally {
    loading.value = false
    refreshing.value = false
    refreshingSystem.value = false
    refreshingComment.value = false
    refreshingLike.value = false
  }
}

// 下拉刷新
const onRefresh = () => {
  loadMessages(true)
}

// 系统消息下拉刷新
const onRefreshSystem = () => {
  loadMessages(true)
}

// 评论消息下拉刷新
const onRefreshComment = () => {
  loadMessages(true)
}

// 点赞消息下拉刷新
const onRefreshLike = () => {
  loadMessages(true)
}

// 上拉加载更多
const onLoad = () => {
  loadMessages()
}

// 消息点击事件
const onMessageClick = (message) => {
  // 标记消息为已读
  message.isRead = true
  
  // 根据消息类型跳转到不同页面
  if (message.type === 'comment' || message.type === 'like') {
    router.push(`/blog/${message.targetId || '1'}`)
  } else if (message.type === 'follow') {
    router.push(`/profile/${message.sender.id}`)
  }
}

onMounted(() => {
  loadMessages()
})
</script>

<style lang="scss" scoped>
.message-page {
  min-height: 100vh;
  background-color: var(--background-color);
  
  .message-list {
    padding-bottom: 16px;
  }
  
  .empty-state {
    padding: 40px 0;
  }
}
</style> 